# from DrissionPage import Chromium
from DrissionPage import ChromiumPage, ChromiumOptions
import re
from logger.main import logger, setup_logger

setup_logger()
co = ChromiumOptions().headless()
page = ChromiumPage(co)
# browser = Chromium()
# page = browser.latest_tab
# 保持加载
page.set.load_mode.none()


def search_procode(procode):
    """
    搜素货号

    Args:
        procode (_type_): _description_
    """
    # 单规格 ab303048
    # 多规格 ab300421
    search_url = f'https://www.abcam.cn/products?keywords={procode}'
    page.get(search_url)

    if has_product(page.title):
        logger.error(f"[Delete] {procode}")
        return

    # 等待login图标删除
    page.wait.ele_deleted('xpath://*[@id="size-information"]/div/div[1]/img')
    # 当login图标删除后主动停止加载
    page.stop_loading()

    # 获取规格和价格

    get_product_des(page, procode)
    return {
        "proname": get_pro_name(page),
        "procode": procode,
        "total": get_spec_and_price(page),
        "picture": get_picture_list(page)
    }

    # res = get_picture_list(page)
    # print(res)


def has_product(text) -> bool:
    """判断是否存在商品

    Args:
        text (_type_): 网页标题

    Returns:
        bool: _description_
    """
    teq = re.compile(r"我们已经不再供应")
    res = teq.search(text)
    if res:
        return True
    return False


def format_spec(string):
    """_summary_

    Args:
        string (_type_): _description_
    """
    spec = remove_first_whitespace(string.split("RMB")[0].replace(',', ''))
    price = string.split("RMB")[1]
    return {
        "spec": spec,
        "price": price,
    }


def remove_first_whitespace(s):
    """删除第一个空白字符

    Args:
        s (_type_): 规格字符串

    Returns:
        _type_: _description_
    """
    return re.sub(r'\s', '', s, count=1)


def get_picture_list(page) -> list:
    """获取商品图片列表"""

    pic_list_els = page.eles('xpath://*[@class="thumbnail-list"]//img',
                             timeout=0)

    list_lenth = len(pic_list_els)
    if list_lenth:
        if list_lenth > 5:
            return [x.attrs['src'] for x in pic_list_els[:5]]
        else:
            return [x.attrs['src'] for x in pic_list_els]

    else:
        pic_dom = page.ele('xpath://*[@class="imagery-main-image-inner"]//img')
        if pic_dom:
            return [pic_dom.attrs['src']]


def get_product_des(page, procode):
    """获取商品详情"""
    # 将商品详情保存为图片
    img_el = page.ele('xpath://*[@id="description_overview"]', timeout=0)
    if img_el:
        img_el.get_screenshot(path="download", name=f"{procode}.png")


def get_spec_and_price(page) -> list:
    """获取规格和价格列表"""
    # 获取dom元素列表
    base_ele = page.eles(
        'xpath://*[@id="size-information"]//*[@id="size-selector"]/div')
    if len(base_ele) == 1:
        print("单规格")
        base_spec = base_ele[0].text.replace(',', '')
        price_el = page.ele('xpath://*[@id="size-information"]/div/span/span')
        base_price = price_el.text.replace(',', '').replace('RMB', '')
        return [{
            "spec": base_spec,
            "price": base_price,
        }]
    else:
        print("多规格")
        total_el = page.eles(
            'xpath://*[@id="size-selector"]/div[1]/label/span/span[2]')

        return [format_spec(item.text) for item in total_el]


def get_pro_name(page):
    pro_title = page.ele(
        'xpath://*[@id="datasheet-header-container"]/header/div[2]/h1').text
    return pro_title
